<template>
  <div class="cesium-draw">
    <div id="cesium-drawer" />
    <canvas id="canvas-a" class="canvas" width="700" height="100"></canvas>
    <canvas id="canvas-b" class="canvas" width="700" height="100"></canvas>
    <div class="mouse-postion">{{ nowPostion.wgs84 }}</div>
    <div class="tool-box">
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="terrainExaggeration" :max="2" /></div> -->
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="relativeHeight" :max="10000" /></div> -->
      <div class="select-box-wrapper"><select-box :options="layerOptions" /></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="shadows">shadows</a-checkbox></div>
      <!-- <div class="select-box-wrapper"><select-box :options="entityToolbarOptions" /></div>
        <div class="select-box-wrapper"><select-box :options="sizeOptions" /></div>
        <div class="select-box-wrapper"><a-checkbox v-model:checked="softShadows">soft shadows</a-checkbox></div>
        <div class="select-box-wrapper"><a-checkbox v-model:checked="terrainShadows">terrain shadows</a-checkbox></div> -->
      <!-- <div class="select-box-wrapper"><a-checkbox v-model:checked="picking">选择</a-checkbox></div> -->
      <div id="menu">
        <!-- <p><button @click="onClick('play')">播放</button></p> -->
        <!-- <p><button @click="onClick('stop')">暂停</button></p> -->
      </div>
    </div>

    <a-dropdown v-if="false">
      <a class="ant-dropdown-link tools" @click.prevent>
        {{ drawingModeText }}
        <DownOutlined />
      </a>
      <template #overlay>
        <a-menu @click="handleMenuClick">
          <a-menu-item v-for="(e, index) in menuOptions" :key="e.key">{{ e.text }}</a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script>
import { DownOutlined, EditOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, watch } from 'vue';
import * as Cesium from '@cesium/Source/Cesium.js';
import MousePosition from '@functional/utils/mousePosition';
import SelectBox from '@components/widgets/select-box';

export default defineComponent({
  name: 'styPointCloud', // 点云渲染
  components: { DownOutlined, EditOutlined, SelectBox },
  setup() {
    return {
      viewer: null,
      onshadows: ()=>{},
      isRepeating: true,
      videoOverlay: true
    };
  },
  data() {
    return {
      layerOptions: [],
      shadows: true,
      nowPostion: {}
    };
  },
  computed: {},
  watch: {
    shadows(val){
      this.onshadows(val)
    }
  },
  mounted() {
    this.initViewer();
  },
  beforeUnmount() {
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },
  methods: {
    handleMenuClick(e) {
      this.drawingMode = e.key;
    },
    handleClick(value) {
      const viewer = this.viewer;
      switch (value) {
        case 'isRepeating':
          break;
      }
    },
    onViewerInited(viewer) {
      let vm = this;
      new MousePosition(viewer, pos => {
        vm.nowPostion = pos;
      });
    },
    initViewer() {
      let vm = this;
      Cesium.Ion.defaultAccessToken = $accessToken.default;
      // let osm = new Cesium.OpenStreetMapImageryProvider({
      //   url: 'https://a.tile.openstreetmap.org/'
      // });
      let osm = new Cesium.ArcGisMapServerImageryProvider({
        // url: '//services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer',
        url: '//services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
      });
      var viewer = new Cesium.Viewer('cesium-drawer', {
        imageryProvider: osm,
        contextOptions: {
          webgl: {
            alpha: true
          }
        },
        animation: false,
        // baseLayerPicker: false,
        fullscreenButton: false,
        vrButton: false,
        homeButton: false,
        timeline: false,
        selectionIndicator: false,
        infoBox: false,
        // 注释时相当于使用默认地形，解开注释相当于使用全球地形
        // terrainProvider: Cesium.createWorldTerrain(),
        shouldAnimate: true
      });

      //开启深度检测
      viewer.scene.globe.depthTestAgainstTerrain = true;

      this.viewer = viewer;
      this.onViewerInited(viewer);

      this.initEffects();

      // this.viewer.flyTo(this.viewer.entities);
    },
    initEffects() {
      let vm = this;
      const viewer = this.viewer;
      var scene = viewer.scene;

      viewer.extend(Cesium.viewerCesium3DTilesInspectorMixin);
      var inspectorViewModel = viewer.cesium3DTilesInspector.viewModel;

      viewer.clock.currentTime = new Cesium.JulianDate(2457522.154792);

      const srv = '//zzgis.com/cdn/3d/';
      const tilesets = [
        {
          name: 'Tileset',
          resource: srv + 'SampleData/Cesium3DTiles/Tilesets/Tileset/tileset.json'
        },
        {
          name: 'Translucent',
          resource: srv + 'SampleData/Cesium3DTiles/Batched/BatchedTranslucent/tileset.json'
        },
        {
          name: 'Translucent/Opaque',
          resource: srv + 'SampleData/Cesium3DTiles/Batched/BatchedTranslucentOpaqueMix/tileset.json'
        },
        {
          name: 'Multi-color',
          resource: srv + 'SampleData/Cesium3DTiles/Batched/BatchedColors/tileset.json'
        },
        {
          name: 'Request Volume',
          resource: srv + 'SampleData/Cesium3DTiles/Tilesets/TilesetWithViewerRequestVolume/tileset.json'
        },
        {
          name: 'Batched',
          resource: srv + 'SampleData/Cesium3DTiles/Batched/BatchedWithBatchTable/tileset.json'
        },
        {
          name: 'Instanced',
          resource: srv + 'SampleData/Cesium3DTiles/Instanced/InstancedWithBatchTable/tileset.json'
        },
        {
          name: 'Instanced/Orientation',
          resource: srv + 'SampleData/Cesium3DTiles/Instanced/InstancedOrientation/tileset.json'
        },
        {
          name: 'Composite',
          resource: srv + 'SampleData/Cesium3DTiles/Composite/Composite/tileset.json'
        },
        {
          name: 'PointCloud',
          resource: srv + 'SampleData/Cesium3DTiles/PointCloud/PointCloudRGB/tileset.json'
        },
        {
          name: 'PointCloudConstantColor',
          resource: srv + 'SampleData/Cesium3DTiles/PointCloud/PointCloudConstantColor/tileset.json'
        },
        {
          name: 'PointCloudNormals',
          resource: srv + 'SampleData/Cesium3DTiles/PointCloud/PointCloudNormals/tileset.json'
        },
        {
          name: 'PointCloudBatched',
          resource: srv + 'SampleData/Cesium3DTiles/PointCloud/PointCloudBatched/tileset.json'
        },
        {
          name: 'PointCloudDraco',
          resource: srv + 'SampleData/Cesium3DTiles/PointCloud/PointCloudDraco/tileset.json'
        }
      ];

      var viewModel = {
        tilesets,
        selectedTileset: undefined,
        shadows: false
      };

      Cesium.knockout.track(viewModel);

      // var toolbar = document.getElementById('toolbar');
      // Cesium.knockout.applyBindings(viewModel, toolbar);

      var tileset;

      Cesium.knockout.getObservable(viewModel, 'shadows').subscribe(function(enabled) {
        viewer.shadows = enabled;
      });

      Cesium.knockout.getObservable(viewModel, 'selectedTileset').subscribe(function(options) {
        if (Cesium.defined(tileset)) {
          scene.primitives.remove(tileset);
        }
        if (!Cesium.defined(options)) {
          inspectorViewModel.tileset = undefined;
          return;
        }

        tileset = viewer.scene.primitives.add(
          new Cesium.Cesium3DTileset({
            url: options.resource
          })
        );

        tileset.readyPromise
          .then(function() {
            inspectorViewModel.tileset = tileset;
            viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0, -2.0, Math.max(100.0 - tileset.boundingSphere.radius, 0.0)));
            // scene.camera.setView({
            //   destination: new Cesium.Cartesian3(1234151.4883992162, -5086036.79436967, 3633328.4278331124),
            //   orientation: {
            //     heading: 5.593695742186853,
            //     pitch: -1.0786797635545216,
            //     roll: 6.27892466154778
            //   }
            // });

            var properties = tileset.properties;
            if (Cesium.defined(properties) && Cesium.defined(properties.Height)) {
              tileset.style = new Cesium.Cesium3DTileStyle({
                color: {
                  conditions: [
                    ['${Height} >= 83', "color('purple', 0.5)"],
                    ['${Height} >= 80', "color('red')"],
                    ['${Height} >= 70', "color('orange')"],
                    ['${Height} >= 12', "color('yellow')"],
                    ['${Height} >= 7', "color('lime')"],
                    ['${Height} >= 1', "color('cyan')"],
                    ['true', "color('blue')"]
                  ]
                }
              });
            }
          })
          .otherwise(function(error) {
            throw error;
          });
      });

      this.layerOptions = tilesets.map(e => {
        return {
          text: e.name,
          onselect() {
            viewModel.selectedTileset = e;
          }
        };
      });

      viewModel.selectedTileset = viewModel.tilesets[0];
      viewModel.shadows = this.shadows;

      this.onshadows = val => {
        viewModel.shadows = val;
      };

      var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);

      handler.setInputAction(function(movement) {
        var feature = inspectorViewModel.feature;
        if (Cesium.defined(feature)) {
          var propertyNames = feature.getPropertyNames();
          var length = propertyNames.length;
          for (var i = 0; i < length; ++i) {
            var propertyName = propertyNames[i];
            console.log(propertyName + ': ' + feature.getProperty(propertyName));
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function(movement) {
        var feature = inspectorViewModel.feature;
        if (Cesium.defined(feature)) {
          feature.show = false;
        }
      }, Cesium.ScreenSpaceEventType.MIDDLE_CLICK);
    }
  }
});
</script>

<style lang="less">
.cesium-draw {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: white;
  font-size: 14px;

  #cesium-drawer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .cesium-viewer-bottom {
      display: none !important;
    }
  }

  .mouse-postion {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 14px;
    padding: 8px 12px;
    line-height: 16px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 3px;
    opacity: 0.8;
  }

  .tools {
    position: absolute;
    top: 57px;
    left: 7px;
    font-size: 14px;
    padding: 8px 12px;
    line-height: 16px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 3px;
    opacity: 0.6;
    transition: all 500ms;
    &:hover {
      opacity: 0.8;
    }
  }
}

.chart-container {
  position: absolute;
  bottom: 7px;
  left: 7px;
  background-color: rgba(0, 0, 0, 0.5);

  #profileChart {
    width: 600px;
    height: 300px;
  }
}
#canvas-a {
  top: 10px;
  display: none;
}

#canvas-b {
  top: 120px;
  display: none;
}
#trailer {
  position: absolute;
  bottom: 75px;
  right: 0;
  width: 320px;
  height: 180px;
}
.tool-box {
  position: absolute;
  top: 70px;
  left: 10px;
  z-index: 9;

  #menu {
    padding-top: 20px;
    button {
      background-color: rgba(0, 0, 0, 0.75);
      border-color: rgba(0, 0, 0, 0);
      cursor: pointer;
      transition: all 500ms;
      &:hover {
        opacity: 0.75;
      }
    }
  }

  .slider-box-wrapper {
    width: 18em;
    padding: 0 10px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
  }

  .select-box-wrapper {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
    width: auto;
  }
}
</style>
